package com.starblink.home.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import com.blankj.utilcode.util.AppUtils
import com.google.android.material.appbar.AppBarLayout
import com.starblink.android.basic.BuildConfig
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.network.base.BaseApiClient
import com.starblink.android.basic.network.base.BaseSiteSwitch
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.home.databinding.*
import com.starblink.home.ui.adapter.HomeBannerAdapter
import com.starblink.home.ui.bean.RvFeedsProductBean
import com.starblink.home.ui.part.*
import com.starblink.rocketreserver.fragment.ProductF
import com.youth.banner.indicator.RectangleIndicator


class NavHomeFragment : BaseTVMFragment<FragmentNavHomeBinding, NavHomeVM>() {

    private lateinit var mPartDiscountMer: PartDiscountMer
    private lateinit var mPartFeeds: PartFeeds
    private lateinit var mBrand: PartBrand
    private var homeI: HomeI? = null
    override fun onPause() {
        super.onPause()
//        pageDisappear(
//            SpmPageDef.Home080Page_10164
//        )
    }


    lateinit var homeApiResultControl: HomeApiResultControl


//    private fun showDialogTest() {
//        val downTimer = FlowCountDownTimer(time = 5)
//        downTimer.start(callBack = {
//
//        }, onFinish = {
//            LoadingDialogManager.get()
//                .showLoading(activity)
//        })
//    }


    override fun initData() {
//        showDialogTest()
        homeI = activity as HomeI
        viewModel.initSomeData()
        //初始化默认搜索底纹词
        PartSearchBar(viewBinding.homeSearch, viewModel).apply {
            handleVM(mContext, this@NavHomeFragment)
        }

        //所有接口的同步汇总+骨架显示处理
        homeApiResultControl = HomeApiResultControl(viewBinding, viewModel).apply {
            initAllDataObserve(mActivity, this@NavHomeFragment, homeI)
        }

        //处理banner
        handlerBanner()

        //处理折扣
        mPartDiscountMer =
            PartDiscountMer(
                viewBinding.layDiscount,
                viewBinding,
                viewModel,
                homeApiResultControl
            ).apply {
                handleVM()
            }

        //品牌处理
        mBrand =
            PartBrand(viewBinding.layBrand, viewBinding, viewModel, homeApiResultControl).apply {
                handleVM()
            }

        //feeds流
        mPartFeeds = PartFeeds(mActivity, viewBinding, viewModel, homeApiResultControl).apply {
            handleVM(mActivity)
        }
        //初始化刷新数据
        //下拉刷新
        viewBinding.page.autoLoadAndRefresh(
            refresh = {
                viewModel.refreshPageData()
            },
            loadMore = {
                viewModel.getFeedsData(isRefresh = false, noData = {
                    if (viewBinding.page.isLoading) {
                        viewBinding.page.finishLoadMore()
                    }
                })
            }
        ).apply {
            viewModel.refreshPageData()
        }
        //注册监听
        registerHomeFlowBus()
        //控制底部导航显示或隐藏
        showOrHideNavBarAnim("NAV_HOME_FIRST_TAG", viewBinding.navHomeRv)
    }

    override fun spmPageId(): Int = SpmPageDef.Home080Page_10164
    override fun isSpmTrackWithLifecycle(): Boolean = true

    var mustBeRefresh = false
    override fun onResume() {
        super.onResume()
//        pageExposure(pageElementValue = SpmPageDef.Home080Page_10164)
        if (mustBeRefresh) {
            //更新曝光数据
            GTrackerAssistUtils.homePageClearQueueSet()
            //刷新首页
            viewModel.refreshPageData()
            val lefTopTag = getLeftTopTag()
            viewBinding.homeSearch.txtEnv.text = lefTopTag
            mustBeRefresh = false
        }
    }


    private fun qaLeftTopText() {

        //左上角标显示当前环境
        if (BaseSiteSwitch.isQaUse()) {
            viewBinding.homeSearch.txtEnv.visible()
            val lefTopTag = getLeftTopTag()
            viewBinding.homeSearch.txtEnv.text = lefTopTag
        } else {
            if (BuildConfig.DEBUG) {
                viewBinding.homeSearch.txtEnv.visible()
                val lefTopTag = getLeftTopTag()
                viewBinding.homeSearch.txtEnv.text = lefTopTag
            } else {
                viewBinding.homeSearch.txtEnv.gone()
            }
        }
    }


    private fun registerHomeFlowBus() {
        //首页自动滑到顶部
        FlowBus.with<Boolean>(FlowConst.HOME_PAGE_SCROLL_TOP).register(this) {
            //执行以下三步重置整个页面的状态
            viewBinding.navHomeRv.scrollToPosition(0)
            scrollToTopOffset()
            viewBinding.appBar.setExpanded(true, false)
        }
        //刷新首页
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            YYLogUtils.e("刷新首页")
            mustBeRefresh = true
        }

        //心愿单添加收藏商品
        FlowBus.with<ProductF>(FlowConst.WISHLIST_ADD_PRODUCT_VIEW).register(this) { prdBus ->
            if (!this.isVisible) {
                changeFeedsCardView(prdBus, true)
            }
        }

        //心愿单删除收藏商品
        FlowBus.with<List<ProductF>>(FlowConst.WISHLIST_DELETE_PRODUCT_VIEW)
            .register(this) { prdBusList ->
                if (prdBusList.size > 5) {
                    viewModel.refreshPageData()
                } else {
                    prdBusList.forEach {
                        changeFeedsCardView(it, false)
                    }
                }
            }

        //刷新折扣
        viewModel.discountMerchantsData.observe(this) {
            mPartDiscountMer.dataChange(it)

        }
        viewModel.brandData.observe(this) {
            mBrand.dataChange(it)
//            mPartFeeds.feedsAdapter.notifyItemRangeChanged(0, mPartFeeds.feedsAdapter.itemCount)
        }
        //刷新feeds流
        viewModel.feedsObserveData.observe(this) {
            mPartFeeds.dataChange(it)
        }

        qaLeftTopText()
    }


    private var behavior: Any? = null
    private fun scrollToTopOffset(offset: Int = 0) {
        if (behavior == null) {
            behavior = (viewBinding.appBar.layoutParams as CoordinatorLayout.LayoutParams).behavior
        }
        if (behavior is AppBarLayout.Behavior) {
            (behavior as AppBarLayout.Behavior).topAndBottomOffset = -offset
        }
    }

    override fun switchNetConfig() {
        super.switchNetConfig()
        startObserve()
    }

    override fun startObserve() {
        qaLeftTopText()
    }

    private fun changeFeedsCardView(prdBus: ProductF, status: Boolean) {
        prdBus.productId?.let { prdBusId ->
            viewModel.feedsObserveData.value?.forEach {
                if (it is RvFeedsProductBean) {
                    it.product.productF.let { prd ->
                        if (prdBusId == prd.productId) {
                            prd.apolloValue("collected", status)
                            viewModel.feedsObserveData.postValue(viewModel.feedsObserveData.value)
                        }
                    }
                }
            }
        }
    }

    private fun getLeftTopTag(): String {
        return "${BaseApiClient.getCurrSvrCfgEnvName()}/${BuildConfig.BUILD_TYPE}/${BaseApiClient.getCurrSiteName()}/${AppUtils.getAppVersionName()}/${AppUtils.getAppVersionCode()}/${UserDataCenter.getLocalCountry()}"

    }

    companion object {
        fun obtainFragment(): NavHomeFragment {
            return NavHomeFragment()
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentNavHomeBinding {
        return FragmentNavHomeBinding.inflate(inflater, container, false)
    }


    private fun handlerBanner() {
        var adapter = HomeBannerAdapter(viewModel.bannerObserveData.value!!, mActivity)
        //添加生命周期观察者
        viewBinding.layHomeBanner.homeBanner.setAdapter(adapter).indicator =
            RectangleIndicator(context)
        viewModel.bannerObserveData.observe(this) {
            if (it.size > 0) {
                viewBinding.layHomeBanner.bannerLay.visible()
            } else {
//                if (viewModel.allApiCompleted.value!![ApiReqStatusEnum.BANNER] == true) {
//                    viewBinding.layHomeBanner.bannerLay.gone()
//                }
                viewBinding.layHomeBanner.bannerLay.gone()
            }
            adapter.notifyDataSetChanged()
        }
    }


    /**
     * 自动播放内容卡片视频
     */


}

